package com.dyw.ycgovfinance.mvp.news.newslist;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.RelativeLayout;

import com.dyw.ycgovfinance.R;
import com.dyw.ycgovfinance.adapter.list.ListAdapterForNews;
import com.dyw.ycgovfinance.adapter.list.ListAdapterForNewsWithPic;
import com.dyw.ycgovfinance.app.CustomApplication;
import com.dyw.ycgovfinance.bean.NewsKindBean;
import com.dyw.ycgovfinance.bean.NewsListBean;
import com.dyw.ycgovfinance.commom.Config;
import com.dyw.ycgovfinance.commom.IntentKey;
import com.dyw.ycgovfinance.mvp.base.BaseFragment;
import com.dyw.ycgovfinance.mvp.news.newsdetail.ActivityNewsDetail;
import com.dyw.ycgovfinance.util.LogUtil;
import com.dyw.ycgovfinance.util.ToastUtil;
import com.dyw.ycgovfinance.util.schedulers.SchedulerProvider;
import com.dyw.ycgovfinance.util.viewutil.PicassoBannerLoader;
import com.dyw.ycgovfinance.widget.ListViewForScrollView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/6/20.
 */

public class FragmentNewsList extends BaseFragment implements NewsListContract.View, PullToRefreshBase.OnRefreshListener2 {


//默认的是isFirstVisibles true ,刚进来的时候分两种情况
    //1.如果切过来的时候 setVisibleHint在OnCreate之前调用，那isFirstVisible为true，这个时候不进行任何操作；
    //等方法执行到onActivityCreated的时候，在执行一次setUserVisibleHint 这个时候把默认的是isFirstVisibles 设为false
    //然后这个时候调用setUserVISIBLEhINT为true  去获取数据
    //2.如果是后面再次切过来，那isFirstVisible已经为false，那就可以直接通过setUserVisibleHint获取数据了

    //代表这个界面是不是第一次被使用
    boolean isFirstUsed = true;
     boolean isGetData = false;
    //是否显示过子fragment
    boolean isShowSonFragment = false;

    private NewsKindBean mNewsKindBean;

    public static final String NEWSKIND = "newskind";


    public static FragmentNewsList newInstance(NewsKindBean newsKindBean) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(NEWSKIND, newsKindBean);

        FragmentNewsList fragment = new FragmentNewsList();
        fragment.setArguments(bundle);


        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenter = new NewsListPresenter(this, SchedulerProvider.getInstance(), CustomApplication.getInstance().getHttpService());
        Bundle bundle = getArguments();
        if (bundle != null) {
            mNewsKindBean = (NewsKindBean) bundle.getSerializable(NEWSKIND);
        }
    }

    NewsListContract.Presenter mPresenter;

    private PullToRefreshScrollView refreshSv;
    private Banner banner;
    private ListViewForScrollView lvNews;
    private RelativeLayout rlEmpty;



    Integer mPageIndex;
    boolean isRefresh;
    boolean canLoad;


    List<NewsListBean> mNewsList = new ArrayList<>();
    ListAdapterForNews mAdapter;
    ListAdapterForNewsWithPic mAdapterForNewsWithPic;

    List<NewsListBean> mNewsBanner = new ArrayList<>();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news_list, container, false);
        initData();
        assignView(view);
        initView();

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //fragment 可见的情况下 进行加载数据。不可见则不加载
        if (getUserVisibleHint() == true) {
            if (isFirstUsed == true) {
                isFirstUsed = false;
                setUserVisibleHint(true);
            }
            //不可见，说明fragment已经初始话完成,就直接把isFirstVisible改为false 再次切过来的时候就直接可以加载数据了
        } else {
            isFirstUsed = false;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        // LogUtil.e("CartVisible");
        if (getUserVisibleHint()) {
            LogUtil.e("MyShuoShuoVisible");
            //如果不是firstvisible才去进行下面的操作  因为第一次很可能出现各种问题
            if (isFirstUsed == false) {
                if (isGetData == false){
                    getOriginalList();
                    if (mNewsKindBean.getName().equals("新闻资讯")) {
                        getNewsBanner();
                    } else {

                    }

                }

            }
        } else {
            LogUtil.e("faXianFragmentVisible");
        }
    }

    @Override
    public void initData() {

    }

    @Override
    public void assignView(View view) {
        banner = (Banner) view.findViewById(R.id.banner);
        refreshSv = (PullToRefreshScrollView) view.findViewById(R.id.refresh_sv);
        lvNews = (ListViewForScrollView) view.findViewById(R.id.lv_news);
        rlEmpty = (RelativeLayout) view.findViewById(R.id.rl_empty);

    }

    @Override
    public void initView() {
        if (mNewsKindBean.getName().equals("新闻资讯")) {
            banner.setVisibility(View.VISIBLE);
        } else {
            banner.setVisibility(View.GONE);
        }
        refreshSv.setOnRefreshListener(this);
        banner.setFocusable(true);
        banner.setFocusableInTouchMode(true);
        banner.requestFocus();

        rlEmpty.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getOriginalList();
            }
        });
        refreshSv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);

        if (mNewsKindBean.getName().equals("图片新闻")) {

            mAdapterForNewsWithPic = new ListAdapterForNewsWithPic(mNewsList,getActivity(),mNewsKindBean.getName());
            lvNews.setAdapter(mAdapterForNewsWithPic);
        } else {
            mAdapter = new ListAdapterForNews(mNewsList,getActivity(),mNewsKindBean.getName());
            lvNews.setAdapter(mAdapter);
        }



        lvNews.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent toNewsDetail = new Intent(getActivity(),ActivityNewsDetail.class);
                toNewsDetail.putExtra(IntentKey.INTENT_KEY_NEWS_ID,String.valueOf(mNewsList.get(position).getId()));
                startActivity(toNewsDetail);
            }
        });
    }


    private void getOriginalList() {
        isRefresh = true;
        mPageIndex = 1;
        getNewsList();
    }

    private void getMoreList() {
        if (canLoad) {
            mPageIndex++;
            getNewsList();
        }
    }

    @Override
    public void getNewsList() {
        if (mNewsKindBean.getName().equals("新闻资讯") || mNewsKindBean.getName().equals("财政文化")) {
            mPresenter.getNewsList(mPageIndex.toString(), Config.DEFAULT_PAGE_SIZE.toString(), mNewsKindBean.getTclass(), "");

        } else {
            mPresenter.getNewsList(mPageIndex.toString(), Config.DEFAULT_PAGE_SIZE.toString(), mNewsKindBean.getTtype(), mNewsKindBean.getTclass());

        }
    }

    @Override
    public void onGetNewsListSuccess(List<NewsListBean> newsList) {
        refreshSv.onRefreshComplete();

        if (isRefresh) {
            mNewsList.clear();
            isRefresh = false;
        }
        rlEmpty.setVisibility(View.GONE);
        refreshSv.setVisibility(View.VISIBLE);

        if (newsList.size() > 0) {
            isGetData = true;
            if (newsList.size() >= Config.DEFAULT_PAGE_SIZE) {
                refreshSv.setMode(PullToRefreshBase.Mode.BOTH);
                canLoad = true;
            } else {
                canLoad = false;
                refreshSv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
            }
            mNewsList.addAll(newsList);

        } else {
            canLoad = false;
            refreshSv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);

            if (mNewsList.size() == 0) {
                isGetData = false;
                refreshSv.setVisibility(View.GONE);
                rlEmpty.setVisibility(View.VISIBLE);
                //refreshSv.setEmptyView(emptylayout);
            } else {
                ToastUtil.show(getActivity(), "已经获取全部数据", 2000);
            }
        }
        if (mNewsKindBean.getName().equals("图片新闻")) {

            mAdapterForNewsWithPic.notifyDataSetChanged();
        } else {
            mAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void onGetNewsListError(String tip) {
        refreshSv.onRefreshComplete();
        ToastUtil.showShort(getActivity(), tip);
        if (isRefresh) {
            mNewsList.clear();
            refreshSv.setVisibility(View.GONE);
            rlEmpty.setVisibility(View.VISIBLE);
        }

        isRefresh = false;
        canLoad = false;

        if (mNewsKindBean.getName().equals("图片新闻")) {

            mAdapterForNewsWithPic.notifyDataSetChanged();
        } else {
            mAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void getNewsBanner() {
        mPresenter.getNewsBanner(mPageIndex.toString(), String.valueOf(5), "102000000000000", "102002000000000");

    }

    @Override
    public void onGetNewsBannerSuccess(List<NewsListBean> newsList) {
        mNewsBanner.clear();
        mNewsBanner.addAll(newsList);

        List<String> newsPicUrls = new ArrayList<>();
        for (NewsListBean newsListBean :newsList){
            newsPicUrls.add(Config.URL_BASE_IN_USE+newsListBean.getUrl());
        }

        banner.setImages(newsPicUrls)
                .setImageLoader(new PicassoBannerLoader())
                .setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
                .start();

        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Intent toNewsDetail = new Intent(getActivity(),ActivityNewsDetail.class);
                toNewsDetail.putExtra(IntentKey.INTENT_KEY_NEWS_ID,String.valueOf(mNewsBanner.get(position).getId()));
                startActivity(toNewsDetail);

               /* Intent intent = new Intent(getActivity(),TopNewsDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable(TopNewsDetailActivity.TAG_TOP_DETAIL,bean);
                intent.putExtras(bundle);
                startActivity(intent);*/
            }
        });
    }

    @Override
    public void onGetNewsBannerError(String tip) {
        ToastUtil.showShort(getActivity(),tip);
        banner.setVisibility(View.GONE);
    }

    @Override
    public void setPresenter(NewsListContract.Presenter presenter) {

    }

    @Override
    public void showLoading() {
        showProgressDialog(false, null);
    }

    @Override
    public void dismissLoading() {
        dismissProgressDialog();
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase pullToRefreshBase) {
        getOriginalList();
        if (mNewsKindBean.getName().equals("新闻资讯")) {
            getNewsBanner();
        } else {

        }
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase pullToRefreshBase) {
        getMoreList();
    }
}
